package com.isoft.service.impl;

import com.isoft.entity.DfoeDfieEntity;
import com.isoft.mapper.DfoeDfieMapper;
import com.isoft.service.DfoeDfieService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

@Service
public class DfoeDfieServiceImpl implements DfoeDfieService {
    private static final Logger logger = LoggerFactory.getLogger(DfoeDfieServiceImpl.class);

    @Autowired
    private DfoeDfieMapper dfoeDfieMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String filePath) throws IOException {
        // 1. 读取文件内容
        Path path = Path.of(filePath);
        String xmlContent = Files.readString(path, StandardCharsets.UTF_8);
        // 2. 记录处理信息
        logger.info("Processing XML file: {}, size: {} bytes", path.getFileName(), Files.size(path));
        // 3. 调用XML处理方法
        // 解析、校验、入库
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }
            DfoeDfieEntity entity = xmlParserUtil.parseXml(xmlContent, DfoeDfieEntity.class);
            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid XML structure");
            }
            dfoeDfieMapper.insertMeta(entity);
            try {
                dfoeDfieMapper.insertFlightBase(entity);
            } catch (org.springframework.dao.DataIntegrityViolationException ex) {
                // 检查是否唯一性约束冲突
                if (ex.getMessage() != null && ex.getMessage().contains("唯一性约束")) {
                    logger.warn("航班ID已存在，跳过插入: {}", entity.getDflt().getFlightId());
                    return "Flight already exists, skipped. Flight ID: " + entity.getDflt().getFlightId();
                } else {
                    throw ex;
                }
            }
            logger.info("✅ 成功处理DFOE-DFIE XML文件，航班ID: {}", entity.getDflt().getFlightId());
            return "Flight data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("❌ XML处理失败", e);
            throw new RuntimeException("Failed to process XML: " + e.getMessage());
        }
    }
}